<?php

namespace App\Console\Commands;

use App\Models\Agent;
use Illuminate\Database\Eloquent\Builder;

class RebuildAgentParentPathId extends ForEachAllAgents
{
    /**
     * 命令名称及签名
     *
     * @var string
     */
    protected $signature = 'migrate:rebuild_agent_parent_path_id';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '修复代理商上级路径中用错了符号的问题';

    public function handle()
    {
        $this->foreachAllAgents(function (Agent $agent) {
            if ($agent->parent_path_id === '') {
                return $agent->parent_path_id;
            }

            $parentPathId = [];
            foreach (array_filter((array) explode(',', $agent->parent_path_id)) as $item) {
                if (false !== strpos($item, '-')) {
                    foreach (explode('-', $item) as $_item) {
                        $parentPathId[] = $_item;
                    }
                } else {
                    $parentPathId[] = $item;
                }
            }

            $parentPathIdStr = implode('-', $parentPathId);
            $agent->update(['parent_path_id' => $parentPathIdStr]);

            return $parentPathIdStr;
        }, function (Builder $builder) {
            $builder->select(['id', 'parent_path_id']);
        });
    }
}
